import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Put,
  Query,
  Request,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { MenuService } from './menu.service';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { ApiOperation, ApiParam, ApiQuery } from '@nestjs/swagger';

@Controller('menu')
export class MenuController {
  constructor(private readonly menuService: MenuService) {}

  @Post()
  @ApiOperation({ summary: '创建菜单' })
  create(@Body() createMenuDto: CreateMenuDto) {
    return this.menuService.create(createMenuDto);
  }

  @Put(':id')
  @ApiOperation({ summary: '更新菜单' })
  @ApiParam({ name: 'id', description: '菜单ID' })
  update(@Param('id') id: number, @Body() updateMenuDto: UpdateMenuDto) {
    return this.menuService.update(id, updateMenuDto);
  }

  @Get()
  @ApiOperation({ summary: '获取菜单列表' })
  findAll() {
    return this.menuService.findAll();
  }

  @Get('tree')
  @ApiOperation({ summary: '获取菜单树形结构' })
  getMenuTree() {
    return this.menuService.getMenuTree();
  }

  @Get('treeAssignPer')
  @ApiQuery({
    name: 'onlyParent',
    required: false,
    type: Boolean,
    description: '是否只获取非按钮的菜单项',
  })
  @ApiOperation({ summary: '获取分配菜单权限树形结构' })
  async getMenuTreeAssignPer(
    @Query('onlyParent') onlyParent?: string,
  ): Promise<any> {
    const filterButtons = onlyParent === 'true';
    return await this.menuService.getMenuTreeAssignPer(filterButtons);
  }

  @Get('routes')
  @ApiOperation({ summary: '获取路由配置' })
  async getRouteConfig(@Request() request) {
    const userId = request.user?.id;
    if (!userId) {
      throw new HttpException('未登录', HttpStatus.UNAUTHORIZED);
    }
    return this.menuService.getRouteConfig(userId);
  }

  @Get(':id')
  @ApiOperation({ summary: '根据ID获取菜单详情' })
  @ApiParam({ name: 'id', description: '菜单ID' })
  findOne(@Param('id') id: number) {
    return this.menuService.findOne(id);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除菜单' })
  @ApiParam({ name: 'id', description: '菜单ID' })
  remove(@Param('id') id: number) {
    return this.menuService.remove(id);
  }
}
